#include <fstream>
#include "protos/addressbook.pb.h"

void PromptForAddress(tutorial::Person *person)
{
    person->set_name("张三");
    person->set_id(123);
    person->set_email("zhangsan@example.com");

    tutorial::Person::PhoneNumber *phone = person->add_phones();
    phone->set_number("13800138000");
    phone->set_type(tutorial::Person::PHONE_TYPE_HOME);
}

int main(int argc, char *argv[])
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;  // 检查版本兼容性

    tutorial::AddressBook address_book;

    // 1. 尝试读取已有文件
    std::fstream input(argv[1], std::ios::in | std::ios::binary);
    if (input && !address_book.ParseFromIstream(&input))
    {
        std::cerr << "解析失败\n";
        return -1;
    }

    // 2. 添加新联系人
    PromptForAddress(address_book.add_people());

    // 3. 写回文件
    std::fstream output(argv[1], std::ios::out | std::ios::trunc | std::ios::binary);
    if (!address_book.SerializeToOstream(&output))
    {
        std::cerr << "写入失败\n";
        return -1;
    }

    google::protobuf::ShutdownProtobufLibrary();  // 可选：清理全局资源
    return 0;
}
